package com.lfc.flowable.controller;

import com.lfc.flowable.domian.AjaxResult;
import com.lfc.flowable.domian.dto.FlowSaveXmlVo;
import com.lfc.flowable.service.ModelService;
import jakarta.annotation.Resource;
import org.flowable.engine.RepositoryService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 模型控制器
 * 获取部署信息(bpmn20.xml)
 */
@RestController
@RequestMapping("/model")
public class ModelController {

    @Resource
    RepositoryService repositoryService;

    @Resource
    ModelService modelService;

    /**
     * 部署file格式
     *
     * @param key
     * @param name
     * @param category
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importFile")
    public AjaxResult importFile(@RequestParam(required = false) String key,
                                 @RequestParam(required = false) String name,
                                 @RequestParam(required = false) String category,
                                 @RequestPart("file") MultipartFile file) throws IOException {
        return modelService.importFile(name, category, file);
    }

    /**
     * 部署xml格式
     *
     * @param vo
     * @return
     */
    @PostMapping("/importXml")
    public AjaxResult importXml(@RequestBody FlowSaveXmlVo vo) {
        InputStream in = new ByteArrayInputStream(vo.getXml().getBytes(StandardCharsets.UTF_8));
        return modelService.importXml(vo.getName(), vo.getCategory(), in);
    }


    /**
     * 点击设计-打开设计器-读取存储的xml
     *
     * @param deployId
     * @return
     */
    @GetMapping("/readXml/{deployId}")
    public AjaxResult readXml(@PathVariable(value = "deployId") String deployId) {
        try {
            return modelService.readXml(deployId);
        } catch (Exception e) {
            return AjaxResult.error("加载xml文件异常");
        }
    }


    /**
     * 获取部署bpmn的流程图
     *
     * @param processDefinitionId 流程定义id
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/{processDefinitionId}", produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getProcessDiagram(@PathVariable String processDefinitionId) throws IOException {
        return modelService.getProcessDiagram(processDefinitionId);
    }

    /**
     * 获取所有流程定义
     */
    @PostMapping("/definitions")
    public AjaxResult getAllProcessDefinitions() {
        return AjaxResult.success(modelService.getAllProcessDefinitions());
    }

    /**
     * 删除流程信息
     *
     * @param deployIds
     * @return
     */
    @PostMapping("/delete/{deployIds}")
    public AjaxResult delete(@PathVariable String[] deployIds) {
        modelService.delete(deployIds);
        return AjaxResult.success();
    }
}
